<?php

namespace Api\Controller;

use Org\Util\ArrayToolkit;

class UploadController extends ApiController
{
    public function _initialize()
    {
        parent::_initialize();
        $this->_me = D('Common/User')->getMe(); // 在线用户
    }
    public function FileUpload() {
        $from = I('request.from');
        $config = C('CUSTOM_UPLOAD_CONFIG');
        $model = D('Common/File')->config($config);
        $info = $model->upload($this->_me['id'], $from, 'Local');
        if(!$info) {
            $this->error($model->getError());
        }
        $this->ajaxReturn($info);
    }

    public function UEditorController()
    {
        $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(CONF_PATH . "ueditor.json")), true);
        $action = I('get.action');

        switch ($action) {
            case 'config':
                $result = $CONFIG;
                break;
            /* 上传图片 */
            case 'uploadimage':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                $result = $this->UEFileUpload($CONFIG, $action);
                break;
            /* 上传涂鸦 */
            case 'uploadscrawl':
                $fieldName = $CONFIG['scrawlFieldName'];
                $data = I($fieldName);
                $result = $this->UEScrawl($CONFIG, $data);
                break;
            /* 列出图片 */
            case 'listimage':
                $result = $this->UEFileList($CONFIG, $action);
                break;
            /* 列出文件 */
            case 'listfile':
                $result = $this->UEFileList($CONFIG, $action);
                break;
            /* 抓取远程文件 */
            case 'catchimage':
                // 该功能已取消
                break;
            default:
                $result = array(
                    'state' => '请求地址出错'
                );
                break;
        }
        /* 输出结果 */
        if (I("callback")) {
            if (preg_match("/^[\w_]+$/", I("callback"))) {
                echo I("callback") . '(' . $result . ')';
            } else {
                $this->ajaxReturn(array(
                    'state' => 'callback参数不合法'
                ));
            }
        } else {
            $this->ajaxReturn($result);
        }
    }

    /**
     * 涂鸦上传
     * @param $config
     * @param $data
     * @return array|bool
     */
    protected function UEScrawl($config, $data) {
        $conf = C('UEDITOR_UPLOAD_CONFIG');
        $conf['maxSize'] = $config['scrawlMaxSize'];
        $model = D('Common/File')->config($conf);
        $file = array(
            'name'=>'scrawl.png',
        );
        $info = $model->upImgByBase64($this->_me['id'], $data, $file, 'ueditor');
        if ($info) {
            $url = main_url('Api/Download/ueditor', array('aid' => think_encrypt($info['id'])));
            $result = array(
                'state' => 'SUCCESS',
                'url' => ltrim($url, '.'),
                'title' => $info['name'],
                'originalName' => $info['name'],
                'type' => '.' . $info['ext'],
                'name' => $info['savename'],
                'size' => $info['size'],
            );
        } else {
            $result['state'] = $model->getError();
        }
        return $result;
    }

    /**
     * 编辑器文件上传
     * @param $config
     * @param $action
     * @return array
     */
    protected function UEFileUpload($config, $action) {
        switch ($action) {
            case 'uploadimage':
                $conf = array(
//                    "pathFormat" => $config['imagePathFormat'],
                    "maxSize" => $config['imageMaxSize'],
                    "allowFiles" => $config['imageAllowFiles']
                );
                $fieldName = $config['imageFieldName'];
                break;
            case 'uploadvideo':
                $conf = array(
//                    "pathFormat" => $config['videoPathFormat'],
                    "maxSize" => $config['videoMaxSize'],
                    "allowFiles" => $config['videoAllowFiles']
                );
                $fieldName = $config['videoFieldName'];
                break;
            case 'uploadfile':
            default:
                $conf = array(
//                    "pathFormat" => $config['filePathFormat'],
                    "maxSize" => $config['fileMaxSize'],
                    "allowFiles" => $config['fileAllowFiles']
                );
                $fieldName = $config['fileFieldName'];
                break;
        }
        $setting = C('UEDITOR_UPLOAD_CONFIG');
        $setting['maxSize'] = $conf['maxSize'];
        $setting['exts'] = ArrayToolkit::trim($conf['allowFiles'], '.');
        $model = D('Common/File')->config($setting);
        $info = $model->upload($this->_me['id'], 'ueditor'); // 开始上传
        $info = $info[$fieldName];
        if ($info) {
            $url = U('Api/Download/ueditor', array('aid' => think_encrypt($info['id'])));
            $fileInfo = array(
                'state' => 'SUCCESS',
                'url' => ltrim($url, '.'),
                'title' => $info['name'],
                'originalName' => $info['name'],
                'type' => '.' . $info['ext'],
                'name' => $info['savename'],
                'size' => $info['size'],
            );
        } else {
            $fileInfo['state'] = $model->getError();
        }
        return $fileInfo;
    }

    // 编辑器文件列表
    protected function UEFileList($config, $action)
    {
        $like = array(
            'ext' => array(),
            '_logic' => 'or',
        );
        switch ($action) {
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $config['fileManagerAllowFiles'];
                $listSize = $config['fileManagerListSize'];
                break;
            /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $config['imageManagerAllowFiles'];
                $listSize = $config['imageManagerListSize'];
                $like['mime'] = array('like', '%image%');
        }
        foreach ($allowFiles as $v) {
            $like['ext'][] = array('eq', trim($v, '.'));
        }
        $like['ext'][] = 'or';
        /* 获取参数 */
        $size = I('size') ? htmlspecialchars(I('size')) : $listSize;
        $start = I('start') ? htmlspecialchars(I('start')) : 0;
        $model = D('Common/File');
        $map = array(
            'userId' => $this->_me['id'],
            'from' => 'ueditor',
        );
        $map['_complex'] = $like;
        $list = $model->where($map)->limit($start, $size)->field('rootpath,savename,savepath,id,name,create_time mtime')->select();
        $count = $model->where($map)->count();
        foreach ($list as &$item) {
            $aid = think_encrypt($item['id']);
            $item['url'] = U('Api/Download/ueditor', array('aid' => $aid,'name'=> $item['name']), '');
        }
        /* 返回数据 */
        $result = array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => $count,
        );
        return $result;
    }
}
